package com.wohuijituan.whcsmerchant.context;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;

import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.nostra13.universalimageloader.utils.StorageUtils;
import com.wohuijituan.whcsmerchant.activity.LoginActivity;
import com.wohuijituan.whcsmerchant.utils.LogUtils;
import com.wohuijituan.whcsmerchant.utils.MyKey;
import com.wohuijituan.whcsmerchant.utils.MyUtile;
import com.zhy.http.okhttp.OkHttpUtils;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.OkHttpClient;

/**
 * 说明：
 * 作者：朱世元
 * 时间： 2016/8/26 17:02
 * 版本：V1.0
 * 修改历史：
 */
public class MyApplication extends Application{
    private static final String TAG = "MyApplication";

    public String getWifiIP() {
        return wifiIP;
    }

    private String wifiIP = "0.0.0.0";
    private String userKey = "";
    private SharedPreferences sp;
    @Override
    public void onCreate() {
        super.onCreate();
        initOkHttp();
        initUserKey();
        initImageLoader();
    }
    /**
     * 初始化ImageLoader基本配置
     */
    private void initImageLoader() {
        File cacheDir = StorageUtils.getOwnCacheDirectory(getApplicationContext(), "imageloader/Cache"); //缓存文件的存放地址
        ImageLoaderConfiguration config = new ImageLoaderConfiguration
                .Builder(getApplicationContext())
                .memoryCacheExtraOptions(480, 800) // max width, max height
                .threadPoolSize(3)//线程池内加载的数量
                .threadPriority(Thread.NORM_PRIORITY - 2)  //降低线程的优先级保证主UI线程不受太大影响
                .denyCacheImageMultipleSizesInMemory()
                .memoryCache(new LruMemoryCache(5 * 1024 * 1024)) //建议内存设在5-10M,可以有比较好的表现
                .memoryCacheSize(5 * 1024 * 1024)
                .discCacheSize(50 * 1024 * 1024)
                .discCacheFileNameGenerator(new Md5FileNameGenerator())
                .tasksProcessingOrder(QueueProcessingType.LIFO)
                .discCacheFileCount(100) //缓存的文件数量
                .discCache(new UnlimitedDiskCache(cacheDir))
                .defaultDisplayImageOptions(DisplayImageOptions.createSimple())
                .imageDownloader(new BaseImageDownloader(getApplicationContext(), 5 * 1000, 30 * 1000)) // connectTimeout (5 s), readTimeout (30 s)
                .writeDebugLogs() // Remove for release app
                .build();
        ImageLoader.getInstance().init(config);//将配置设置给ImageLoader的单例
    }
    private void initUserKey(){
        sp = getSharedPreferences(MyKey.userConfig, MODE_PRIVATE);
        userKey = sp.getString("userKey", "");
        new Thread(new Runnable() {
            @Override
            public void run() {
                wifiIP = GetNetIp();
                LogUtils.e(TAG,wifiIP);
            }
        }).start();
    }

    /**
     * 初始化okhttp
     */
    private void initOkHttp(){
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
//                .addInterceptor(new LoggerInterceptor("TAG"))
                .connectTimeout(10000L, TimeUnit.MILLISECONDS)
                .readTimeout(10000L, TimeUnit.MILLISECONDS)
                        //其他配置
                .build();

        OkHttpUtils.initClient(okHttpClient);
    }
    public String getUserKey() {
        return userKey;
    }

    public void setUserKey(String userKey) {
        this.userKey = userKey;
    }
    /**
     * 获取用户当前ip
     */
    public  String getLocalIpAddress(){
        ConnectivityManager connectMgr = (ConnectivityManager) this
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        //获取当前联网信息
        NetworkInfo info = connectMgr.getActiveNetworkInfo();
        if(info !=null &&info.getType() == ConnectivityManager.TYPE_WIFI){//为wifi联网
//            //获取wifi服务
//            WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
//            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
//            int ipAddress = wifiInfo.getIpAddress();
//            return MyUtile.intToIp(ipAddress);
            return wifiIP;
        }else if (info !=null && info.getType() ==  ConnectivityManager.TYPE_MOBILE){//GPRS联网
            try {
                for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
                    NetworkInterface intf = en.nextElement();
                    for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                        InetAddress inetAddress = enumIpAddr.nextElement();
                        LogUtils.e(TAG, inetAddress.getAddress().length + "");
                        if (!inetAddress.isLoopbackAddress()&&!inetAddress.isLinkLocalAddress()) {
                            return inetAddress.getHostAddress();
                        }
                    }
                }
            }
            catch (SocketException ex) {
                LogUtils.e(TAG,ex.toString());
            }
        }
        return "0.0.0";
    }
    /**
     * 检查当前网络是否可用
     *
     * @param
     * @return
     */

    public boolean isNetworkAvailable(Context activity)
    {
        Context context = activity.getApplicationContext();
        // 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        if (connectivityManager == null)
        {
            return false;
        }
        else
        {
            // 获取NetworkInfo对象
            NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();

            if (networkInfo != null && networkInfo.length > 0)
            {
                for (int i = 0; i < networkInfo.length; i++)
                {
                    System.out.println(i + "===状态===" + networkInfo[i].getState());
                    System.out.println(i + "===类型===" + networkInfo[i].getTypeName());
                    // 判断当前网络状态是否为连接状态
                    if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED)
                    {
                        return true;
                    }
                }
            }
        }
        return false;
    }
    /**
     * 获取当前手机机型
     * @return
     */
    public String getUserModel(){
        return android.os.Build.MODEL;//手机机型
    }
//    public static String GetNetIp() {
//        URL infoUrl = null;
//        InputStream inStream = null;
//        String ipLine = "";
//        HttpURLConnection httpConnection = null;
//        try {
//            infoUrl = new URL("http://www.cmyip.com/");
//            URLConnection connection = infoUrl.openConnection();
//            httpConnection = (HttpURLConnection) connection;
//            int responseCode = httpConnection.getResponseCode();
//            LogUtils.e(TAG,"responseCode:"+responseCode);
//            if (responseCode == HttpURLConnection.HTTP_OK) {
//                inStream = httpConnection.getInputStream();
//                BufferedReader reader = new BufferedReader(
//                        new InputStreamReader(inStream, "utf-8"));
//                StringBuilder strber = new StringBuilder();
//
//                String line = null;
//                while ((line = reader.readLine()) != null)
//                    LogUtils.e(TAG,"line:"+line);
//                    strber.append(line + "\n");
//
//                Pattern pattern = Pattern
//                        .compile("((?:(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))\\.){3}(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d))))");
//                Matcher matcher = pattern.matcher(strber.toString());
//                if (matcher.find()) {
//                    ipLine = matcher.group();
//                }
//            }
//
//        } catch (MalformedURLException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        } finally {
//            try {
//                inStream.close();
//                httpConnection.disconnect();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//        LogUtils.e(TAG,"**"+ipLine);
//        return ipLine;
//    }
public static String GetNetIp()
{
    String IP = "0.0.0.0";
    try
    {
        String address = "http://ip.taobao.com/service/getIpInfo2.php?ip=myip";
        URL url = new URL(address);
        HttpURLConnection connection = (HttpURLConnection) url
                .openConnection();
        connection.setUseCaches(false);

        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK)
        {
            InputStream in = connection.getInputStream();

// 将流转化为字符串
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(in));

            String tmpString = "";
            StringBuilder retJSON = new StringBuilder();
            while ((tmpString = reader.readLine()) != null)
            {
                retJSON.append(tmpString + "\n");
            }

            JSONObject jsonObject = new JSONObject(retJSON.toString());
            String code = jsonObject.getString("code");
            if (code.equals("0"))
            {
                JSONObject data = jsonObject.getJSONObject("data");
                IP = data.getString("ip");
//                        + "(" + data.getString("country")
//                        + data.getString("area") + "区"
//                        + data.getString("region") + data.getString("city")
//                        + data.getString("isp") + ")";

                Log.e("提示", "您的IP地址是：" + IP);
            }
            else
            {
                IP = "";
                Log.e("提示", "IP接口异常，无法获取IP地址！");
            }
        }
        else
        {
            IP = "";
            Log.e("提示", "网络连接异常，无法获取IP地址！");
        }
    }
    catch (Exception e)
    {
        IP = "";
        Log.e("提示", "获取IP地址时出现异常，异常信息是：" + e.toString());
    }
    return IP;
}
}
